<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, reactive, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message, Modal } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { Apis } from '#/api';
import { Page } from '#/components/page';
import { useRender } from '#/hooks/useRender';
import { DICT_TYPE } from '#/utils/dict';

import DictTypeTree from './components/dict-type-tree.vue';
import EditDictDataModal, {
  type EditDictDataModalState,
} from './components/edit-dict-data-modal.vue';
import EditDictTypeModal, {
  type EditDictTypeModalState,
} from './components/edit-dict-type-modal.vue';

const [BaseEditDictDataModal, baseEditDictDataModalApi] = useVbenModal({
  connectedComponent: EditDictDataModal,
});

const [BaseEditDictTypeModal, baseEditDictTypeModalApi] = useVbenModal({
  connectedComponent: EditDictTypeModal,
});

const gridRef = ref<any>(null);

const searchParams = reactive({
  dictType: '',
});

const dictTypeTreeRef = ref<InstanceType<typeof DictTypeTree>>();

const dictTypeTreeData = ref<any[]>([]);

const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'Input',
      fieldName: 'label',
      label: '字典标签',
    },
    {
      component: 'Input',
      fieldName: 'value',
      label: '字典键值',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '正常',
            value: '1',
          },
          {
            label: '封禁',
            value: '2',
          },
        ],
        placeholder: '请选择',
      },
      fieldName: 'status',
      label: '记录状态',
    },
  ],
  showCollapseButton: true,
  submitOnEnter: true,
  wrapperClass: 'grid-cols-1 md:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  showOverflow: true,
  keepSource: true,
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true,
  },
  scrollX: {
    enabled: true,
  },
  scrollY: {
    enabled: true,
  },
  columns: [
    { type: 'checkbox', width: 50 },
    { type: 'seq', title: '序号', width: 50 },
    { field: 'dictType', title: '字典类型', minWidth: 120, showOverflow: true },
    {
      field: 'label',
      title: '字典标签',
      minWidth: 120,
      showOverflow: true,
    },
    {
      field: 'value',
      title: '字典键值',
      minWidth: 120,
      showOverflow: true,
    },
    {
      field: 'status',
      title: '记录状态',
      width: 80,
      slots: {
        default: ({ row }) =>
          useRender.renderSwitch(row.status, async (checked) => {
            const hideLoading = message.loading('正在修改状态...');
            Apis.system.dictData
              .update({
                pathParams: {
                  id: row.id,
                },
                data: {
                  status: checked ? 0 : 1,
                },
              })
              .then(() => {
                row.status = checked ? 0 : 1;
              })
              .finally(() => {
                hideLoading();
              });
          }),
      },
    },
    {
      field: 'isDefault',
      title: '是否默认',
      width: 80,
      slots: {
        default: ({ row }) =>
          useRender.renderDict(row.isDefault, DICT_TYPE.sysCommonWhether),
      },
    },
    { field: 'extend1', title: '扩展字段1', width: 100 },
    { field: 'extend2', title: '扩展字段2', width: 100 },
    { field: 'remark', title: '备注', minWidth: 200 },
    {
      field: 'action',
      title: '操作',
      width: 110,
      fixed: 'right',
      slots: { default: 'action' },
    },
  ],
  rowClassName: 'cursor-pointer',
  height: 'auto',
  pagerConfig: {
    enabled: false,
  },
  rowConfig: {
    isCurrent: true,
  },
  proxyConfig: {
    ajax: {
      query: async (_, formValues) => {
        return await Apis.system.dictData.getList({
          params: {
            dictType: searchParams.dictType,
            ...formValues,
          },
        });
      },
    },
  },
};

const selectedRows = ref<any[]>([]);

const [Grid, gridApi] = useVbenVxeGrid({
  gridClass: 'h-full',
  formOptions,
  gridOptions,
  gridEvents: {
    cellClick({ row }) {
      gridApi.grid.toggleCheckboxRow(row);
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
    checkboxChange() {
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
    checkboxAll() {
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
  },
});

function handleEdit(row?: any) {
  baseEditDictDataModalApi.setData<EditDictDataModalState>({
    isUpdate: !!row,
    record: row || {},
  });
  baseEditDictDataModalApi.open();
}

function handleDelete(rows: any[]) {
  if (rows.length === 0) {
    message.error('请选择要删除的记录');
    return;
  }
  Modal.confirm({
    title: '确定要删除吗？',
    content: '删除后将无法恢复',
    onOk: () => {
      if (rows.length === 1) {
        message.error('请选择单个记录进行删除');
        return;
      }
      return rows;
    },
  });
}

function handleEditDictType(row?: Record<string, any>) {
  baseEditDictTypeModalApi.setData<EditDictTypeModalState>({
    isUpdate: !!row,
    record: row || {},
  });
  baseEditDictTypeModalApi.open();
}

function handleDeleteDictType(rows: any[]) {
  if (rows.length === 0) {
    message.error('请选择要删除的记录');
    return;
  }
  Modal.confirm({
    title: '确定要删除吗？',
    content: '删除后将无法恢复',
    onOk: () => {
      return rows;
    },
  });
}

const selectDataTypeNode = ref<any>({});
function handleNodeClick(row?: any) {
  selectDataTypeNode.value = row;
  searchParams.dictType = row?.code || '';
  gridApi.reload();
}

async function loadDataByDictType() {
  const res = await Apis.system.dictType.getList();
  dictTypeTreeData.value = res.list;
}

onMounted(async () => {
  await loadDataByDictType();
});
</script>

<template>
  <Page content-class="h-full">
    <BaseEditDictDataModal />
    <BaseEditDictTypeModal />

    <a-row :gutter="[12, 0]" class="h-full">
      <a-col :span="6" class="h-full">
        <div class="h-full w-full rounded-lg bg-white p-2">
          <DictTypeTree
            ref="dictTypeTreeRef"
            :data="dictTypeTreeData"
            show-action
            @delete="handleDeleteDictType"
            @edit="handleEditDictType"
            @node-click="handleNodeClick"
            @refresh="loadDataByDictType"
          />
        </div>
      </a-col>

      <a-col :span="18" class="h-full">
        <div class="flex h-full flex-1 flex-col">
          <Grid
            ref="gridRef"
            :table-title="
              selectDataTypeNode.name
                ? `${selectDataTypeNode.name}（${selectDataTypeNode.code}）`
                : '字典数据列表'
            "
          >
            <template #toolbar-tools>
              <a-space>
                <a-button type="primary" @click="handleEdit()"> 新增 </a-button>
                <a-button
                  :disabled="selectedRows.length === 0"
                  danger
                  type="primary"
                  @click="handleDelete(selectedRows)"
                >
                  批量删除
                </a-button>
              </a-space>
            </template>

            <template #action="{ row }">
              <div v-if="row.id">
                <a-button
                  size="small"
                  type="link"
                  @click.stop="handleEdit(row)"
                >
                  编辑
                </a-button>
                <a-button
                  danger
                  size="small"
                  type="link"
                  @click.stop="handleDelete(row)"
                >
                  删除
                </a-button>
              </div>

              <div v-else>
                <a-button
                  size="small"
                  type="link"
                  @click.stop="handleEdit(row)"
                >
                  保存
                </a-button>
                <a-button
                  danger
                  size="small"
                  type="link"
                  @click.stop="handleDelete(row)"
                >
                  移除
                </a-button>
              </div>
            </template>
          </Grid>
        </div>
      </a-col>
    </a-row>
  </Page>
</template>
